﻿using MediatR;
using MyRabbit.Application.Command;
using MyRabbit.Application.Dtos;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler
{
    public class BreedQueryCommandHandler : IRequestHandler<BreedQueryCommand, APIResult<BreedDTO>>
    {

        /// <summary>
        /// 养殖仓储
        /// </summary>
        private readonly IRepository<Breed> breedRep;
        /// <summary>
        /// 产品仓储
        /// </summary>
        private readonly IRepository<Product> proRep;


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="proRep"></param>
        /// <param name="breedRep"></param>
        public BreedQueryCommandHandler(IRepository<Product> proRep,IRepository<Breed> breedRep)
        {
            this.proRep = proRep;
            this.breedRep = breedRep;
        }

        public async Task<APIResult<BreedDTO>> Handle(BreedQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<BreedDTO> result = new APIResult<BreedDTO>();
            result.Code = Codes.查询成功;
            result.Message = Codes.查询成功.ToString();
            var breed = from a in await proRep.GetAllAsync()
                        join b in await breedRep.GetAllAsync() on a.BreedId equals b.BreedId
                        where a.ProductId == request.ProductId
                        select new BreedDTO
                        {
                            BreedId = b.BreedId,
                            Variety = b.Variety,
                            Source = b.Source,
                            FeedingDays = b.FeedingDays,
                            FeedingBrand = b.FeedingBrand,
                            FeedingName = b.FeedingName,
                            SaleDate = b.SaleDate
                        };
            if (breed.Count() == 0)
            {
                result.Code = Codes.查询失败;
                result.Message = Codes.查询失败.ToString();
                return await Task.FromResult(result);
            }

            result.Data = breed.FirstOrDefault();

            return await Task.FromResult(result);
        }
    }
}
